package com.then.basic.socket;

import java.lang.ref.WeakReference;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**
 *
 * Created by longyi on 16/7/27.
 */
public class SafeHandler extends Handler {
    public interface MessageProcessor {
        void handleMessage(Message msg);
    }

    public static final MessageProcessor EMPTY_MESSAGE_PROCESSOR = new MessageProcessor() {
        @Override
        public void handleMessage(Message msg) {

        }
    };

    private WeakReference<MessageProcessor> weakReference;
    public SafeHandler(MessageProcessor ref) {
        weakReference = new WeakReference<>(ref);
    }

    public SafeHandler(Looper looper, MessageProcessor ref) {
        super(looper);
        weakReference = new WeakReference<>(ref);
    }

    @Override
    public final void handleMessage(Message msg) {
        super.handleMessage(msg);
        MessageProcessor processor = weakReference.get();
        if (processor != null) {
            processor.handleMessage(msg);
        }
    }
}
